package org.example.service.impl;

import org.example.api.AccountService;
import org.example.entity.OrderTbl;
import org.example.mapper.OrderTblMapper;
import org.example.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderTblMapper orderTblMapper;

    @Autowired
    private AccountService accountService;

    private static Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Override
    public OrderTbl create(String userId, String commodityCode, int orderCount){
        logger.info("准备为{}创建一个订单,商品编号为{}，数量为{}", userId,commodityCode, orderCount);
        // 1 计算总金额
        int orderMoney = calculate(commodityCode, orderCount);
        accountService.debit(userId, orderMoney);
        OrderTbl order = new OrderTbl();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(orderCount);
        order.setMoney(orderMoney);
        orderTblMapper.insert(order);
        // INSERT INTO orders ...
        return order;
    }

    private int calculate(String commodityCode, int orderCount) {


        // 我们现在没有商品的表，在此我们把商品的价格定死
        int prodPrice = 0 ;
        if("HUAWEI_0001".equals(commodityCode)){

            // 华为时 100
            prodPrice = 100;
        }else if ("XIAOMI_002".equals(commodityCode)){

            // 小米时 200
            prodPrice = 200 ;
        }else {


            prodPrice = 1000 ; // 其他为 1000
        }
        return orderCount * prodPrice ;
    }
}
